﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Product;
using Provenance.Read.Api.Application.Command.Provenance;
using Provenance.Read.Api.Dto.Product;

namespace Provenance.Read.Api.Application.CommandHandler.Provenance
{
    public class GetProductInfoCommandHandler : IRequestHandler<GetProductInfoCommand, ApiResult<PagingResult<IList<GetProductInfoResponseDTO>>>>
    {
        private readonly IProductInfoRepository _productInfoRepository;
        private readonly ILogger<GetProductInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        public GetProductInfoCommandHandler(IProductInfoRepository productInfoRepository, ILogger<GetProductInfoCommandHandler> logger, IMapper mapper)
        {
            _productInfoRepository = productInfoRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<PagingResult<IList<GetProductInfoResponseDTO>>>> Handle(GetProductInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = await _productInfoRepository.GetAllAsync(x => !x.IsDeleted);
                var result=_mapper.Map<IList<GetProductInfoResponseDTO>>(list);
                var response = result.OrderBy(x => x.ProductInfoId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                var pagingResult = new PagingResult<IList<GetProductInfoResponseDTO>>()
                {
                    TotalCount = list.Count(),
                    TotalPage = (int)Math.Ceiling(list.Count() / (double)request.PageSize),
                    Data = response
                };
                return ApiResult<PagingResult<IList<GetProductInfoResponseDTO>>>.Success(pagingResult);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error in GetProductInfoCommandHandler: " + ex.Message);
                return ApiResult<PagingResult<IList<GetProductInfoResponseDTO>>>.Failure(ex.Message);
            }
        }
    }
}
